package org.yxing.palpalgps.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

/**
 * @deprecated
 * @author yuxing
 *
 */
public class Util {
    public static String request(String url, List<BasicNameValuePair> params) 
            throws UnsupportedEncodingException, ClientProtocolException, IOException, HttpException {
        
        String data = null;
        HttpPost httpPost = new HttpPost(url);
        if (params != null)
            httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        HttpResponse resp = new DefaultHttpClient().execute(httpPost);
        
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            InputStream in = resp.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuffer buffer = new StringBuffer();
            char[] buf = new char[512];
            int l;
            while ((l = reader.read(buf)) != -1)
                buffer.append(buf, 0, l);
            data = buffer.toString();
            reader.close();
            in.close();
        } else {
            String message = resp.getStatusLine().getStatusCode() + " : " + EntityUtils.toString(resp.getEntity());
            throw new HttpException(message);
        }

        return data;
    }
    
    
}
